package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmSensitiveService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1.非空判断
        dto.checkParam();
        //2.分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();
        //2.1 根据状态查询
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //2.2 根据关键字查询
        if (!StringUtils.isEmpty(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //2.3 根据频道id查询
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //2.4 根据开始和结束时间查询
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }

        //2.5 根据登录用户id查询
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = super.page(page, queryWrapper);

        //3.返回数据结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Autowired
    private WmSensitiveService wmSensitiveService;
    /**
     * 保存-修改-提交草稿为一体的方法
     * 主方法
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult submit(WmNewsDto dto) {
        //TODO
        WmNews bean = BeanUtil.toBean(dto, WmNews.class);
        WmUser user = WmThreadLocalUtil.getUser();
        List<String> images = dto.getImages();
        String string = images.stream()
                .reduce((a, b) -> a + ", " + b)
                .orElse("");
        bean.setImages(string);
        bean.setUserId(user.getId());
        bean.setCreatedTime(new Date());
        LambdaQueryWrapper<WmNews> wmNewsLambdaQueryWrapper = Wrappers.<WmNews>lambdaQuery(bean);
        WmNews wmNews = wmNewsMapper.selectOne(wmNewsLambdaQueryWrapper);

        if (wmNews != null) {
            Integer newsId = wmNews.getId();
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, newsId);
            wmNewsMaterialMapper.delete(queryWrapper);
        }

        if (dto.getType() == -1) {
            // 将JSON字符串转换为JSONArray
            JSONArray jsonArray = new JSONArray(bean.getContent());
            List<String> totalPath=new ArrayList<>();
            // 遍历JSONArray
            for (int i = 0; i < jsonArray.length(); i++) {
                // 获取每一个JSONObject
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                // 检查"type"是否为"image"
                if ("image".equals(jsonObject.getString("type"))) {
                    // 获取"value"字段的值（即图片路径）
                    String imagePath = jsonObject.getString("value");
                    totalPath.add(imagePath);
                }
            }

            if (totalPath.size()==0){
                bean.setType((short) 0);
                wmNewsMapper.insert(bean);
            }

            if (totalPath.size()>0 && totalPath.size()<3){
                String totalImagePath=null;
                for (String pathUrl : totalPath) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(pathUrl+", ");
                    if (sb.length()>0){
                        sb.setLength(sb.length()-2);
                    }
                    totalImagePath=sb.toString();
                }
                bean.setImages(totalImagePath);
                bean.setType((short) 1);
                wmNewsMapper.insert(bean);
            }

            if (totalPath.size()>=3){
                String totalImagePath=null;
                for (String pathUrl : totalPath) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(pathUrl+", ");
                    if (sb.length()>0){
                        sb.setLength(sb.length()-2);
                    }
                    totalImagePath=sb.toString();
                }
                bean.setImages(totalImagePath);
                bean.setType((short) 3);
                wmNewsMapper.insert(bean);
            }

        } else {
            wmNewsMapper.insert(bean);
        }

        if (dto.getStatus() != 0) {
            WmNewsMaterial wmMaterial = new WmNewsMaterial();
            WmMaterial wmMaterial1 = null;
            // 将JSON字符串转换为JSONArray
            JSONArray jsonArray = new JSONArray(bean.getContent());
            // 遍历JSONArray
            for (int i = 0; i < jsonArray.length(); i++) {
                // 获取每一个JSONObject
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                // 检查"type"是否为"image"
                if ("image".equals(jsonObject.getString("type"))) {
                    // 获取"value"字段的值（即图片路径）
                    String imagePath = jsonObject.getString("value");
                    LambdaQueryWrapper<WmMaterial> queryWrapper1 = Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUrl, imagePath);
                    wmMaterial1 = wmMaterialMapper.selectOne(queryWrapper1);
                    if (ObjectUtil.isNotEmpty(wmMaterial1)) {
                        wmMaterial.setNewsId(bean.getId());
                        wmMaterial.setType((short) 1);
                        wmMaterial.setMaterialId(wmMaterial1.getId());
                    }
                    wmNewsMaterialMapper.insert(wmMaterial);
                    try {
                        wmSensitiveService.informationReview(bean);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            try {
                wmSensitiveService.informationReview(bean);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        //6.返回数据
        return ResponseResult.okResult("发布文章完成");
    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //TODO
        //根据id查询用户是否存在
        if (dto.getId()==null){
            return ResponseResult.errorResult(501,"文章id不存在");
        }
        WmNews news = this.getById(dto.getId());
        if (news==null){
            return ResponseResult.errorResult(1002,"文章不存在");
        }
        if (news.getStatus()!=9){
            return ResponseResult.errorResult(501,"文章未发布");
        }
        news.setEnable(dto.getEnable());
        this.updateById(news);
        amqpTemplate.convertAndSend(
                WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,
                WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_ROUTINGKEY,
                news.getArticleId()
        );

        return ResponseResult.okResult("文章上下架完成");
    }
}
